﻿using FM.Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FM.Infrastructure
{
    public class FinanceContext : DbContext
    {
        public FinanceContext() : base("FinanceContext") 
        { 

        }

        public DbSet<Category> Categories { get; set; }

        public DbSet<Expense> Expenses { get; set; }

        public DbSet<User> Users { get; set; }

        public DbSet<Role> Roles { get; set; }

        public virtual void Commit()
        {
            base.SaveChanges();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
           .HasMany(u => u.Roles)
           .WithMany(r => r.Users)
           .Map(m =>
           {
               m.ToTable("RoleMemberships");
               m.MapLeftKey("UserName");
               m.MapRightKey("RoleName");
           });
        }
    }

    public class FinanceContextInitializer : DropCreateDatabaseIfModelChanges<FinanceContext>
    {
        protected override void Seed(FinanceContext context)
        {
            var roles = new List<Role>{
                new Role{RoleName = "Administrator"},
                new Role{RoleName = "User"}               
            };

            roles.ForEach(r => context.Roles.Add(r));
        }
    }
}
